<script setup lang="ts">
import { ref, computed, h } from 'vue';
import { NDrawer, NDrawerContent, NDescriptions, NDescriptionsItem, NDataTable, NTag, NButton, NSpace } from 'naive-ui';

defineOptions({
  name: 'QueryResultDrawer'
});

const visible = ref(false);
const queryResult = ref<Api.DataPlatform.QueryResultDTO | null>(null);

// 打开抽屉
function open(result: Api.DataPlatform.QueryResultDTO) {
  queryResult.value = result;
  visible.value = true;
}

// 关闭抽屉
function close() {
  visible.value = false;
  queryResult.value = null;
}

// 表格列定义
const columns = computed(() => {
  if (!queryResult.value?.columns) return [];
  return queryResult.value.columns.map(col => ({
    title: col.name,
    key: col.name,
    width: 150,
    ellipsis: { tooltip: true },
    render: (row: Record<string, any>) => {
      const value = row[col.name];
      if (value === null || value === undefined) {
        return h(NTag, { type: 'warning' }, () => 'NULL');
      }
      return String(value);
    }
  }));
});

defineExpose({
  open
});
</script>

<template>
  <NDrawer v-model:show="visible" :width="1200" placement="right">
    <NDrawerContent title="查询结果" closable>
      <div v-if="queryResult" class="flex-col gap-16px">
        <!-- 查询信息 -->
        <NDescriptions bordered :column="2" size="small">
          <NDescriptionsItem label="执行时间">
            {{ queryResult.executionTime }}ms
          </NDescriptionsItem>
          <NDescriptionsItem label="结果行数">
            {{ queryResult.total }}
          </NDescriptionsItem>
          <NDescriptionsItem label="列数">
            {{ queryResult.columns?.length || 0 }}
          </NDescriptionsItem>
          <NDescriptionsItem label="查询历史ID">
            {{ queryResult.historyId || '-' }}
          </NDescriptionsItem>
        </NDescriptions>

        <!-- 结果表格 -->
        <div class="flex-1 overflow-hidden">
          <NDataTable
            :columns="columns"
            :data="queryResult.rows"
            :scroll-x="columns.length * 150"
            :max-height="600"
            size="small"
            striped
          />
        </div>
      </div>

      <template #footer>
        <NSpace justify="end">
          <NButton @click="close">关闭</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
